package com.toolbox.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.toolbox.bo.AccountBO;
import com.toolbox.dal.repository.InfraRoleDORepository;
import com.toolbox.dal.repository.InfraRoleMenuDORepository;
import com.toolbox.dal.repository.InfraUserRoleDORepository;
import com.toolbox.dto.InfraRoleDTO;
import com.toolbox.pages.Pager;
import com.toolbox.req.InfraRoleReq;
import com.toolbox.service.InfraRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author Mango
 * @since 2023-12-01
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class InfraRoleServiceImpl implements InfraRoleService {

    /**
     * 角色表 服务类
     */
    @Autowired
    private InfraRoleDORepository repository;

    /**
     * 角色菜单表 服务类
     */
    @Autowired
    private InfraRoleMenuDORepository roleMenuDORepository;

    /**
     * 用户角色表 服务类
     */
    @Autowired
    private InfraUserRoleDORepository userRoleDORepository;

    @Override
    public Pager<InfraRoleDTO> getRolePage(Integer pageIndex, Integer pageSize, String keywords) {
        return repository.getRolePage(pageIndex, pageSize, keywords);
    }

    @Override
    public List<InfraRoleDTO> getRoleList() {
        return repository.getRoleList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Long createRole(InfraRoleReq req, AccountBO bo) {
        Long roleId = repository.createRole(req, bo);

        if (!CollUtil.isEmpty(req.getMenuIds())) {
            // 处理角色与菜单的关系
            roleMenuDORepository.save(roleId, req.getMenuIds(), bo);
        }

        return roleId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Long updateRoleById(InfraRoleReq req, AccountBO bo) {
        Long roleId = repository.updateRoleById(req, bo);

        if (!CollUtil.isEmpty(req.getMenuIds())) {
            // 处理角色与菜单的关系
            roleMenuDORepository.save(roleId, req.getMenuIds(), bo);
        }

        return roleId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void removeById(Long id) {
        // 1、删除角色信息
        repository.removeById(id);

        // 2、删除角色与菜单的关系
        roleMenuDORepository.removeByRoleId(id);

        // 3、删除角色与用户的关系
        userRoleDORepository.removeByRoleId(id);
    }

}
